from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate,logout,login
from  django.conf import settings
import os,re,json
from repository import models
from host import tables
from host import task_manager

from  repository import admin
#分页
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from utils import host_utils

# from backend.task_manager import  MultiTaskManger
from backend import audit


# @login_required
def audit_session(request):

    # log_date_path = "%s/%s" %(settings.SESSION_AUDIT_LOG_DIR,log_date)
    # log_file_dirs = os.listdir(log_date_path)
    # session_ids = [re.search("\d+",i).group() for i in log_file_dirs
    # session_objs = models.SessionTrack.objects.filter(id__in=session_ids)

    if request.method == "GET":

        page_number = request.GET.get('page_num')
        if page_number == None or '':
            page_number = 20
        print('=== page_number ===',page_number)

        session_objs_list = tables.table_filter(request,admin.SessionTrackAdmin,models.SessionTrack)

        order_res = tables.get_orderby(request, session_objs_list, admin.SessionTrackAdmin)
        paginator = Paginator(order_res[0], page_number)

        page = request.GET.get('page')
        try:
            session_objs = paginator.page(page)
        except PageNotAnInteger:
            session_objs = paginator.page(1)
        except EmptyPage:
            session_objs = paginator.page(paginator.num_pages)

        table_obj = tables.TableHandler(request,
                                        models.SessionTrack,
                                        admin.SessionTrackAdmin,
                                        session_objs,
                                        order_res
                                        )

        return render (request, 'host/user_audit_session.html', {'table_obj': table_obj, 'paginator': paginator,'page_number':page_number,'admin_list_filter':admin.SessionTrackAdmin.list_filter})

    # session_objs = models.SessionTrack.objects.all() 取出所有session 会话信息。
    # return render(request, 'host/user_audit_session.html', locals())

# @login_required
def audit_cmd(request,session_id):
    print('==session_id==',session_id)

    if request.method == "GET":

        page_number = request.GET.get('page_num')
        if page_number == None or '':
            page_number = 20

        print('=== page_number ===',page_number)

        order_res = models.AuditLog.objects.filter(session_id=session_id)
        # print('===order_res===',order_res)
        # return render(request,"host/user_audit_cmd.html",locals())
        # AuditLog_objs_list = tables.table_filter(request,admin.AuditLogAdmin,models.AuditLog)

        order_res = tables.get_orderby(request, order_res, admin.AuditLogAdmin)
        print('----> page_number ---',page_number)
        paginator = Paginator(order_res[0], int(page_number))

        page = request.GET.get('page')
        try:
            audit_cmd_objs = paginator.page(page)
        except PageNotAnInteger:
            audit_cmd_objs = paginator.page(1)
        except EmptyPage:
            audit_cmd_objs = paginator.page(paginator.num_pages) # page_number

        table_obj = tables.AuditLogTableHandler(request,
                                        models.AuditLog,
                                        admin.AuditLogAdmin,
                                        audit_cmd_objs,
                                        order_res
                                        )

        return render (request, 'host/user_audit_cmd.html', {'table_obj': table_obj, 'paginator': paginator,'page_number':page_number})


# @login_required
def hosts(request):

    selected_g_id = request.GET.get('selected_group')
    if selected_g_id:
        if selected_g_id.isdigit():
            selected_g_id = int(selected_g_id)


    recent_logins = host_utils.recent_accssed_hosts(request)  # 最近-登录
    print('---- recent_logins --->',recent_logins)

    return render(request,'host/hosts.html',{'login_user':request.user,
                                             'selected_g_id': selected_g_id,
                                             'active_node':"/host/hosts/?selected_group=-1",
                                             'recent_logins':recent_logins,
                                             'webssh':settings.SHELLINABOX})

# @login_required
def token_gen(request):
    #token_type = request.POST.get('token_type')
    token = host_utils.Token(request)
    token_key = token.generate()
    return HttpResponse(token_key)


def batch_cmd_execute(request):

    recent_tasks = models.Task.objects.filter(user_id=1).order_by('-id')[:10]


    return render(request,'host/host_multitask_cmd.html',{'login_user':request.user,
                                              #'host_groups':valid_hosts,
                                              'recent_tasks': recent_tasks,
                                              'active_node':'/host/multitask'}
                  )

# @login_required
def host_multitask_cmd(request):
    '''通过API 传送文本框里的命令并 获取后端返回的 --> 任务ID。'''
    #print '==post:',request.POST
    multi_task = task_manager.MultiTask('run_cmd',request)
    task_id = multi_task.run()
    print('====task_id====',task_id)  # 返回了任务的ID，前端的JS要根据ID轮循这去取结果。

    if task_id:
        return HttpResponse(task_id)
    else:
        return HttpResponse("TaskCreatingError")


# @login_required
def multitask_res(request):
    multi_task = task_manager.MultiTask('get_task_result',request)
    task_result = multi_task.run()
    return HttpResponse(task_result)

